<script setup lang="ts">
import { ref, onUnmounted } from 'vue'
// 导入校验规则
import { mobileRules, passwordRules, codeRules } from '@/utils/rules'
// 导入账号密码api
import { loginByPassword, sendMobileCode, loginByMobile } from '@/api/user'
// 导入用户store
import { useUserStore } from '@/stores'
// 导入router
import { useRoute, useRouter } from 'vue-router'
import { showSuccessToast, showToast, type FormInstance } from 'vant'

const clickRight = () => {
  // 点击右侧执行
  console.log(123)
}
// 是否同意网站的使用协议
const agree = ref(false)
// 1.动态切换密码框眼睛图标，控制是否显示密码
const isShowPass = ref(false)
// 2.准备账号密码的响应变量
const mobile = ref('13230000001')
const password = ref('abc12345')
// 3.定义切换密码和短信登录响应变量isPass：true 密码登录 | false 短信登录
const isPass = ref(true)
//
const store = useUserStore()
// 跳转页面使用
const router = useRouter()
// 获取路由参数
const route = useRoute()
console.log(route)
console.log(router)

const code = ref('') //验证码
const time = ref(0) //倒计时时间
const form = ref<FormInstance>() //表单实例
let timeId: number //定时器id
// 3.登录兜底校验：点击登录回调函数
const login = async () => {
  console.log('校验通过')
  if (!agree.value) return showToast('请勾选我已同意')
  // 进行登陆
  const res = isPass.value
    ? await loginByPassword(mobile.value, password.value)
    : await loginByMobile(mobile.value, code.value)
  console.log(res)

  try {
    const res = await loginByPassword(mobile.value, password.value)
    console.log('登陆成功', res)
    // 路由不跳转的原因居然在这？？？
    store.setUser(res.data)
    router.push((route.query.returnUrl as string) || '/user')

    showSuccessToast('登录成功')
  } catch (err) {
    console.log(err)
  }
}

// 2.发送验证码
const send = async () => {
  // 已经倒计时time的值大于0，60s内不能重复发送验证码
  if (time.value > 0) return
  try {
    await form.value?.validate('mobile')
    const data = await sendMobileCode(mobile.value, 'login')
    showSuccessToast('发送成功')
    code.value = data.code
    time.value = 60
    // 倒计时
    timeId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) window.clearInterval(timeId)
    }, 1000)
  } catch (err) {
    console.log('登陆失败')
  }
}
onUnmounted(() => {
  // 销毁避免内存泄露
  window.clearInterval(timeId)
})
</script>
<template>
  <!-- 父组件使用 -->
  <cp-nav-bar title="登录" lefttext="" righttext="注册" @click-right="clickRight" />
  <!-- 登录布局 -->
  <div class="login">
    <!-- 1.头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ !isPass ? '密码登录' : '短信验证码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- == 2.form 表单 == -->
    <van-form autocomplete="off" @submit="login">
      <van-field
        v-if="isPass"
        v-model="mobile"
        name="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <van-field v-else v-model="code" :rules="codeRules" placeholder="短信验证码">
        <template #button>
          <!-- 下面的语法表示 active 是否存在取决于其后面数据属性的真假值 -->
          <span :class="{ active: time > 0 }" @click="send">{{
            time > 0 ? `${time}s后再次发送` : '发送验证码'
          }}</span>
          <!-- 思路2：倒计时禁用按钮 -->
          <!-- <button @click="send" :disabled="time > 0">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </button> -->
        </template>
      </van-field>
      <van-field
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="isShowPass ? 'text' : 'password'"
      >
        <!-- 具名插槽 -->
        <template #button>
          <cp-icon
            @click="isShowPass = !isShowPass"
            :name="`login-eye-${isShowPass ? 'on' : 'off'}`"
          ></cp-icon>
        </template>
      </van-field>

      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <van-button native-type="submit" block round type="primary">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
  </div>
</template>

<style lang="scss" scoped>
.active {
  color: red;
}
.login {
  padding-top: 46px;
  &-head {
    padding: 30px 30px 50px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  .van-form {
    padding: 0 14px;
    .cp-cell {
      height: 52px;
      padding: 14px 16px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .van-checkbox {
        a {
          color: var(--cp-primary);
          padding: 0 5px;
        }
      }
    }
  }
}
</style>
